package webserver;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Contains get request from client
 */
public class HttpRequest {

    private static final String REQUESTED_PAGE = "requestedPage";
    private static final String SELECTED_VALUE = "on";

    private static Pattern PAGE_WITH_PARAMS = Pattern
	    .compile("GET (/([^\\?]*)(\\?(.*))?) HTTP/.*");

    private Map<String, String> map = new HashMap<String, String>();
    private List<String> paramsAsList = new ArrayList<String>();

    private boolean parseLine(String request) {
	if (request == null)
	    return false;
	Matcher matcher = PAGE_WITH_PARAMS.matcher(request);
	if (matcher.find()) {
	    String page = matcher.group(2);
	    if (page.trim().length() == 0) {
		map.put(HttpRequest.REQUESTED_PAGE, Consts.INDEX);
	    } else {
		map.put(HttpRequest.REQUESTED_PAGE, page);
	    }
	    String params = matcher.group(4);
	    if (params != null && params.trim().length() != 0) {
		String[] keyValueString = params.split("&");
		for (String keyValue : keyValueString) {
		    String[] keyValueArray = keyValue.split("=");
		    map.put(keyValueArray[0].trim(), keyValueArray[1].trim());
		}
	    }
	    return true;
	} else {
	    return false;
	}
    }

    public String getValueByName(String name) {
	return map.get(name);
    }

    public List<String> getSelectedParams() {
	List<String> res = new ArrayList<String>();
	for (Entry<String, String> ent : map.entrySet()) {
	    if (ent.getValue().equals(SELECTED_VALUE)) {
		res.add(ent.getKey());
	    }
	}
	return res;
    }

    public String getPage() {
	return map.get(REQUESTED_PAGE);
    }

    public String getSSID() {
	return map.get(Consts.PARAM_SSID);
    }

    @Override
    public String toString() {
	return "HttpRequest [Params=" + this.map + "]";
    }

    public void add(String s) {
	paramsAsList.add(s);
    }

    public void parse() {
	for (String str : paramsAsList) {
	    if (parseLine(str))
		break;
	}
    }
}
